<template>
<et-dropdown :id="id" :close-on-click="true" max-height="10rem" :width="width">
  <a slot="anchor" :data-toggle="id">
    {{ txt }}
    <et-icon :name="icon" />
  </a>
  <ul slot="contents" class="menu vertical">
    <li v-for="(item, idx) in items" :key="idx">
      <label :class="`et-${type}`">
        <input v-if="type === 'radio'" type="radio" :value="item.val" v-model="radioMdl" />
        <input v-else type="checkbox" :value="item.val" v-model="checkboxMdl" />
        <span></span>
        {{ $t(item.txt) }}
      </label>
    </li>
    <li class="ops">
      <a class="float-left" @click="okHandler">{{ $t('common.ok') }}</a>
      <a class="float-right" @click="resetHandler">{{ $t('common.reset') }}</a>
    </li>
  </ul>
</et-dropdown>
</template>

<script>
import EtDropdown from '../EtDropdown';
import { EtIcon } from '../../widgets';

export default {

  components: {
    EtDropdown,
    EtIcon
  },

  props: {
    id: {
      type: String,
      required: true
    },
    txt: {
      type: String,
      require: true
    },
    activeIcon: {
      type: String,
      default: 'filter'
    },
    passiveIcon: {
      type: String,
      default: 'filter-empty'
    },
    items: {
      type: Array,
      require: true
    },
    type: {
      type: String,
      required: true,
      validator(value) {
        return ['radio', 'checkbox'].indexOf(value) !== -1;
      }
    },
    width: {
      type: String
    }
  },

  data() {
    return {
      radioMdl: '',
      checkboxMdl: [],
      enableFilter: false
    };
  },

  computed: {
    icon() {
      return this.enableFilter && (this.radioMdl || this.checkboxMdl.length > 0) ? this.activeIcon : this.passiveIcon;
    }
  },

  methods: {

    okHandler() {

      $(`#${this.id}`).foundation('close');

      if (this.type === 'radio' && this.radioMdl.length === 0) {
        return;
      }

      if (this.type === 'checkbox' && this.checkboxMdl.length === 0) {
        this.resetHandler();
        return;
      }

      this.enableFilter = true;

      this.$emit('tableFilter', {
        id: this.id,
        payload: this.type === 'radio' ? this.radioMdl : this.checkboxMdl
      });

    },

    resetHandler() {
      if (this.type === 'radio') {
        this.radioMdl = '';
      } else {
        this.checkboxMdl = [];
      }

      this.enableFilter = false;
      $(`#${this.id}`).foundation('close');

      this.$emit('tableFilter', {
        id: this.id,
        payload: null
      });
    },

    clear() {
      this.radioMdl = '';
      this.checkboxMdl = [];
      this.enableFilter = false;
    }

  }

};
</script>
